package org.lex.elec.model.dao;

import java.sql.Connection;
import java.util.Collection;

import org.apache.commons.dbutils.QueryRunner;
import org.lex.elec.model.AppException;
import org.lex.elec.model.ErrorCode;

public abstract class BaseDao<T> {
	private final Connection conn;
	private QueryRunner queryRunner;

	protected BaseDao(Connection conn) {
		super();
		this.conn = conn;
	}

	protected final Connection getConnection() {
		return this.conn;
	}

	protected final QueryRunner getQueryRunner() {
		if (null == this.queryRunner) {
			this.queryRunner = new QueryRunner();
		}
		return this.queryRunner;
	}

	protected final <D> D singleResult(Collection<D> c) throws AppException {
		if (null == c || c.isEmpty()) {
			throw new AppException(ErrorCode.NOT_EXISTS, "no data avaliable");
		}
		// FIXME if more than 1 data, throw exception?
		return c.iterator().next();
	}
}